const process = require("process");
const path = require("path");
const fs = require("fs");
const express = require("express");
const router = express.Router();

router.get("/", (req, res) => {
  res.redirect("/static/index.html");
});

router.get("/local-ip", (req, res, next) => {
  const interfaces = require("os").networkInterfaces();
  for (let devName in interfaces) {
    const iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return res.json({ ip: alias.address });
      }
    }
  }
});

// 获取输入图片列表
router.get("/input", (req, res) => {
  const fileNodes = fs.readdirSync(
    path.join(process.cwd(), "app", "input", "images")
  );
  return res.json(fileNodes);
});

// 获取输入图片
router.get("/input/:name", (req, res) => {
  const imgPath = path.join(
    process.cwd(),
    "app",
    "input",
    "images",
    req.params.name
  );
  const stream = fs.createReadStream(imgPath);
  stream.on("data", (chunk) => {
    res.status(200).write(chunk);
  });
  stream.on("end", () => {
    res.status(200).end();
  });
});

// 获取输出图片
router.get("/output/:name", (req, res) => {
  const imgPath = path.join(process.cwd(), "app", "output", req.params.name);
  const stream = fs.createReadStream(imgPath);
  stream.on("data", (chunk) => {
    res.status(200).write(chunk);
  });
  stream.on("end", () => {
    res.status(200).end();
  });
});

module.exports = router;
